// 集中管理模型和关联关系
const { sequelize } = require('../config/database');
const User = require('./User');
const Fruit = require('./Fruit');
const Warehouse = require('./Warehouse');
const FruitWarehouse = require('./FruitWarehouse');

// 定义多对多关联关系
// 水果和仓库通过 FruitWarehouse 关联表实现多对多关系

// Fruit belongsToMany Warehouse
Fruit.belongsToMany(Warehouse, {
  through: FruitWarehouse,
  foreignKey: 'fruit_id',
  otherKey: 'warehouse_id',
  as: 'warehouses'
});

// Warehouse belongsToMany Fruit
Warehouse.belongsToMany(Fruit, {
  through: FruitWarehouse,
  foreignKey: 'warehouse_id',
  otherKey: 'fruit_id',
  as: 'fruits'
});

// 直接访问关联表
Fruit.hasMany(FruitWarehouse, {
  foreignKey: 'fruit_id',
  as: 'fruitWarehouses'
});

Warehouse.hasMany(FruitWarehouse, {
  foreignKey: 'warehouse_id',
  as: 'warehouseFruits'
});

FruitWarehouse.belongsTo(Fruit, {
  foreignKey: 'fruit_id',
  as: 'fruit'
});

FruitWarehouse.belongsTo(Warehouse, {
  foreignKey: 'warehouse_id',
  as: 'warehouse'
});

module.exports = {
  sequelize,
  User,
  Fruit,
  Warehouse,
  FruitWarehouse
};

